/**Trigger Name: NMRLeadShareTrig
 * Author: Accenture
 * Requirement/Project Name: NMR
 * Requirement Description: Lead should be shared with Sales Rep
 */
 
 trigger NMRLeadShareTrig on Lead (after insert, after update) {
    
    Id nmrLeadRT = RecordTypeHelper.GetRecordTypeID('Lead', 'NMR Lead');
    Id nmrLeadCustIdRT = RecordTypeHelper.GetRecordTypeID('Lead', 'NMR Lead with CustomerId');
    list<LeadShare> leadShareInsert = new list<LeadShare>();
    list<LeadShare> leadShareDelete = new list<LeadShare>();
    list<Id> leadIdList = new list<Id>();
    
    for(Lead lead : Trigger.new) {
        string ownercheck = string.valueOf(lead.ownerId);
        if((lead.RecordTypeId == nmrLeadRT || lead.RecordTypeId == nmrLeadCustIdRT) && ownercheck.substring(0,3)!='00G' &&
           lead.NMR_Sales_Rep__c != NULL && (Trigger.IsInsert || (Trigger.IsUpdate && lead.NMR_Sales_Rep__c != trigger.oldMap.get(lead.Id).NMR_Sales_Rep__c)))
        {
            LeadShare leadShare = new LeadShare();
                leadShare.LeadId = lead.Id; //Lead Record being shared
                leadShare.UserOrGroupId = lead.NMR_Sales_Rep__c; //Secondary record owner
                leadShare.LeadAccessLevel = 'Edit'; //Access   
            leadShareInsert.add(leadShare);
            
            if(Trigger.IsUpdate)
            {
                leadIdList.add(lead.Id);                
            }
        }
    }
    if(leadIdList.size()>0){ 
    leadShareDelete = [Select Id from LeadShare where leadId in: leadIdList and RowCause != 'Owner' ];
     }
 
    try{
        //delete existing lead share records       
        if(leadShareDelete.size() > 0)
            delete leadShareDelete;
        
        //Insert Sharing rule
        if(leadShareInsert.size() > 0)
            insert leadShareInsert;             
            
    }catch (DMLException e){
        system.debug('DML Exception: ' + e.getMessage());
    }
           
}